package com.will.rest.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.will.common.dto.OrderDto;
import com.will.common.dto.OrderRequest;
import com.will.common.dto.ProductDto;
import com.will.common.response.AjaxResult;
import com.will.rest.service.IOrderService;
import com.will.rest.service.IRepoService;
import com.will.rest.service.IRestOrderService;
import io.seata.core.context.RootContext;
import io.seata.core.exception.TransactionException;
import io.seata.spring.annotation.GlobalTransactional;
import io.seata.tm.api.GlobalTransactionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class RestOrderServiceImpl implements IRestOrderService {

    @Autowired
    private IOrderService orderService;
    @Autowired
    private IRepoService repoService;

    @Override
    @GlobalTransactional(timeoutMills = 300000, name = "my_test_tx_group", rollbackFor = Exception.class)
    public AjaxResult handleBusiness(OrderRequest orderRequest) throws TransactionException {
        log.info("开始全局事务：xid=" + RootContext.getXID());
        // 扣减库存
        ProductDto productDto = new ProductDto();
        productDto.setProductCode(orderRequest.getProductCode());
        productDto.setCount(orderRequest.getCount());
        AjaxResult repoRes = repoService.decreaseRepo(productDto);
        log.info("扣减库存结果:{}", JSONObject.toJSONString(repoRes));
        // 创建订单
        OrderDto orderDto = new OrderDto();
        orderDto.setUserId(orderRequest.getUserId());
        orderDto.setOrderAmount(orderRequest.getAmount());
        orderDto.setOrderCount(orderRequest.getCount());
        orderDto.setProductCode(orderRequest.getProductCode());
        AjaxResult orderRes = orderService.createOrder(orderDto);
        log.info("创建订单结果:{}", JSONObject.toJSONString(orderRes));
        if (repoRes.get("code").equals(500) || orderRes.get("code").equals(500)) {
            // 事务回滚
            log.info("事务回滚");
            GlobalTransactionContext.reload(RootContext.getXID()).rollback();
        }
        return AjaxResult.success();
    }
}
